package com.lzy.crm.wechat.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lzy.crm.base.date.DateUtil;
import com.lzy.crm.base.util.JsonUtil;
import com.lzy.crm.base.util.Md5Util;
import com.lzy.crm.base.util.StringUtil;
import com.lzy.crm.domain.BankCard;
import com.lzy.crm.domain.Crowd;
import com.lzy.crm.domain.Order;
import com.lzy.crm.domain.User;
import com.lzy.crm.service.BankCardService;
import com.lzy.crm.service.OrderService;
import com.lzy.crm.service.ProfitService;
import com.lzy.crm.service.UserService;
import com.lzy.crm.util.BootJsonResponse;
import com.lzy.crm.util.UserConstants;
import com.lzy.crm.vo.PlayerInfo;
import com.lzy.crm.wechat.consts.WechatPayProperties;
import com.lzy.crm.wechat.util.WeixinUtil;


/**
 * 玩家控制器
 * @author chenshiping
 *
 */
@Controller
@RequestMapping("/wechat")
public class PlayerController {
	
	Logger logger= Logger.getLogger(PlayerController.class);
	
	@Resource
	UserService userService;
	
	@Resource
	OrderService orderService;
	
	@Resource
	private BankCardService bankCardService;
	
	@Resource
	private ProfitService profitService;
	
	@RequestMapping("/player")  
	public String player(HttpServletRequest request,ModelMap model) {
		return "wechat/user/player_info"; 
	}
	/**
	 * 升级成为代理商
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/player_to_user")  
	public String playerToUser(HttpServletRequest request,ModelMap model) {
		User user =(User)request.getSession().getAttribute("userSession");
		// 订单信息
		if(user==null||StringUtil.isEmpty(user.getOpenid())
				||StringUtil.isEmpty(user.getUnionid())
				){
			// 不构成支付条件
			model.put("appid", WechatPayProperties.getAppId());
			model.put("redirectUri", WechatPayProperties.getRedirectUri()+"?page=wechat/player_to_user.html");
			return "wechat/index2"; 
		}
		// 邀请人个数
		int inviteNub = UserConstants.INVITE_NUB;
		
		List<Order> orderList = orderService.getOrderList(user.getOpenid(),String.valueOf(UserConstants.BECOME_AGENT_MONEY));
		if(!StringUtil.equals(user.getUserLevel(), UserConstants.USER_LEVEL_TGDS)){
			model.put("msg", "您已经是代理商，了解更多合作信息，请联系客服~");
			return "wechat/user/player_to_user"; 
		}
		List<User> userList =userService.getUserListByParentId(user.getId());
		if((orderList==null||orderList.size()==0)&&
				(userList.size()<=inviteNub )){
			model.put("msg", "&nbsp;&nbsp;请先充值一笔大于"+UserConstants.BECOME_AGENT_MONEY+"的订单&nbsp; 或者 &nbsp;&nbsp;&nbsp; 邀请 "+inviteNub+"位有效游戏玩家~~");
		}
		return "wechat/user/player_to_user"; 
	}

	/**
	 *  玩家成为代理商
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(path="/player_to_user_save",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String playerToUserSave(HttpServletRequest request,ModelMap model) {
		BootJsonResponse response=new BootJsonResponse();
		try {
			User newUser =(User)request.getSession().getAttribute("userSession");
			// 订单信息
			if(newUser==null||StringUtil.isEmpty(newUser.getOpenid())
					||StringUtil.isEmpty(newUser.getUnionid())
					){
				// 不构成支付条件
				model.put("appid", WechatPayProperties.getAppId());
				model.put("redirectUri", WechatPayProperties.getRedirectUri()+"?page=wechat/player_to_user.html");
				return "wechat/index2"; 
			}
			
			if(!StringUtil.equals(newUser.getUserLevel(), UserConstants.USER_LEVEL_TGDS)){
				response.setMessage("您已经是代理商，请登陆后台查看信息~~");
				return JsonUtil.toJson(response);
			}
			String userName = request.getParameter("userName");
			String phone = request.getParameter("phone");
			String email = request.getParameter("email");
			String outUserName = request.getParameter("outUserName");
			
			
			
			if(StringUtil.isNotEmpty(email)){
				List<User> emailList = userService.getUserListByEmailAndPwd(email);
				if(emailList.size()>0){
					response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
					response.setMessage("邮箱已被占用，请换一个邮箱 ");
					return JsonUtil.toJson(response) ;
				}
			}
			List<User> phoneList =userService.getUserListByPhoneAndPwd(phone);
			if(phoneList.size()>0){
				response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				response.setMessage("手机号码已被占用，请换一个手机号码 ");
				return JsonUtil.toJson(response) ;
			}
			newUser.setUserName(userName);
			newUser.setPhone(phone);
			newUser.setUserLevel(UserConstants.DEF_USER_LEVEL);
			newUser.setUserType(UserConstants.USER_TYPE_AGENT);
			newUser.setEmail(email);
			newUser.setStatus(UserConstants.USER_STATUS_NORMAL);
			newUser.setPassword(Md5Util.encode("123456"));
			String remark= newUser.getRemark()+"-->微信端转代理商用户";
			if(remark.length()>74){
				remark=remark.substring(0, 70);
			}
			newUser.setRemark(remark);
			newUser.setOutUserName(outUserName);
			newUser.setUpdateTime(new Date());
			userService.updateByPrimaryKeySelective(newUser);
			
			// 写入银行卡信息
			String bankName = request.getParameter("bankName");
			String bankUserNo = request.getParameter("bankUserNo");
			String bankUserName = request.getParameter("bankUserName");
			if(!StringUtil.isEmpty(bankName)||!StringUtil.isEmpty(bankUserNo)
					||!StringUtil.isEmpty(bankUserName)){
				BankCard bankCard = new BankCard();
				List<BankCard> bankCardList = bankCardService.getBankCardListByUserId(newUser.getId().toString());
				if(bankCardList!=null&&bankCardList.size()>0){
					bankCard = bankCardList.get(0);
					bankCard.setBankName(bankName);
					bankCard.setBankUserNo(bankUserNo);
					bankCard.setBankUserName(bankUserName);
					bankCard.setUpdateTime(new Date());
					bankCardService.updateByPrimaryKeySelective(bankCard);
				}else{
					bankCard.setUserId(newUser.getId());
					bankCard.setBankName(bankName);
					bankCard.setBankUserNo(bankUserNo);
					bankCard.setBankUserName(bankUserName);
					bankCard.setCardFlag("1"); // 默认启用
					bankCard.setCreateTime(new Date());
					bankCardService.insertSelective(bankCard);
				}
			}
			
			
			response.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
			response.setMessage("操作成功,默认密码123456，请登陆代理商后台及时更换密码~");
			logger.info("操作成功");
		} catch (Exception e) {
			response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			response.setMessage("操作失败，请联系管理员~");
			logger.error(" 成为代理商错误 "+e);
		}
		return JsonUtil.toJson(response); 
	}
	
	/**
	 * 用户激活成推广大使
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/player_to_user_tgds")  
	public String playerToUserTgds(HttpServletRequest request,ModelMap model) {
		User user =(User)request.getSession().getAttribute("userSession");
		// 订单信息
		if(user==null||StringUtil.isEmpty(user.getOpenid())
				||StringUtil.isEmpty(user.getUnionid())
				){
			// 不构成支付条件
			model.put("appid", WechatPayProperties.getAppId());
			model.put("redirectUri", WechatPayProperties.getRedirectUri()+"?page=wechat/player_to_user.html");
			return "wechat/index2"; 
		}
		// 邀请人个数
		int inviteNub = UserConstants.INVITE_NUB_TGDS;
		List<User> userList =userService.getUserListByParentId(user.getId());
		if((userList.size()<=inviteNub )){
			model.put("msg", "&nbsp;&nbsp 邀请 "+inviteNub+"位有效游戏玩家~~");
		}
		model.put("userList", userList);
		return "mobile/user/user_activate"; 
	}
	
	
	/**
	 *  玩家成为代理商
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(path="/player_to_user_tgds_save",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String playerToUserTgdsSave(HttpServletRequest request,ModelMap model) {
		BootJsonResponse response=new BootJsonResponse();
		try {
			User newUser =(User)request.getSession().getAttribute("userSession");
			// 订单信息
			if(newUser==null||StringUtil.isEmpty(newUser.getOpenid())
					||StringUtil.isEmpty(newUser.getUnionid())
					){
				// 不构成支付条件
				model.put("appid", WechatPayProperties.getAppId());
				model.put("redirectUri", WechatPayProperties.getRedirectUri()+"?page=wechat/login.html");
				return "wechat/index2"; 
			}
			if(StringUtil.equals(newUser.getUserType(), UserConstants.USER_TYPE_AGENT)){
				if(!StringUtil.equals(newUser.getUserLevel(), UserConstants.USER_LEVEL_TGDS)){
					response.setMessage("您已经是代理商，请登陆后台查看信息~~");
					return JsonUtil.toJson(response);
				}
			}
			newUser.setUserType(UserConstants.USER_TYPE_AGENT);
			newUser.setStatus(UserConstants.USER_STATUS_NORMAL);
			userService.updateByPrimaryKeySelective(newUser);
			response.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
			response.setMessage("激活成功~");
			logger.info("操作成功");
		} catch (Exception e) {
			response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			response.setMessage("操作失败，请联系管理员~");
			logger.error(" 成为代理商错误 "+e);
		}
		return JsonUtil.toJson(response); 
	}
	
	
	
	
	@RequestMapping("/player_invite") 
	public String player_invite(HttpServletRequest request ,ModelMap model) {
		String gameId = request.getParameter("gameId");
		model.put("invite", false);
		boolean isweixin = WeixinUtil.isWeiXin(request);
		if(isweixin){
			User user =(User)request.getSession().getAttribute("userSession");
			
			// 登陆
			if(user==null||StringUtil.isEmpty(user.getOpenid())
					||StringUtil.isEmpty(user.getUnionid())
					){
				// 调用微信登陆
				model.put("appid", WechatPayProperties.getAppId());
				model.put("redirectUri", WechatPayProperties.getRedirectUri()+"?page=wechat/player_invite.html?gameId="+gameId);
				return "wechat/index2"; 
			}
			if(StringUtil.isEmpty(gameId)){
				gameId= user.getGameUserId().toString();
			}
			PlayerInfo playerInfo = userService.getPlayerInfo(null, user.getUnionid());
			request.getSession().setAttribute("playerSession",playerInfo);
			if(StringUtil.equals(gameId, user.getGameUserId().toString())){
				model.put("invite", true);
			}
			String startTime ="";
			if(user.getBitthday()!=null){
				startTime = DateUtil.formatDateWithTime(user.getBitthday());
			}else if(user.getCreateTime()!=null){
				startTime = DateUtil.formatDateWithTime(user.getCreateTime());
				user.setBitthday(user.getCreateTime());
				userService.updateByPrimaryKeySelective(user);
			}else{
				startTime = DateUtil.getCurrentLongTime();
				user.setBitthday(new Date());
				user.setCreateTime(new Date());
				userService.updateByPrimaryKeySelective(user);
			}
			Integer GameCount = profitService.getProfitGameCount(user.getId(),startTime, UserConstants.OUT_START_TIME ,UserConstants.OUT_END_TIME );
			model.put("money", GameCount*0.05);
		}
	
		return "wechat/advice/invite_award";
	}
	
	//玩家体现功能
	@RequestMapping(path="/player_kiting",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String player_kiting(HttpServletRequest request,ModelMap model) throws Exception{
		try{
			User user =(User)request.getSession().getAttribute("userSession");
			model.put("statusCode", BootJsonResponse.STATUS_CODE_SUCCESS);
			PlayerInfo playerInfo = userService.getPlayerInfo(null, user.getUnionid()) ;
			if(playerInfo ==null){
				model.put("msg", "请先下载游戏才能分享体现~");
				return JsonUtil.toJson(model);
			}
			Integer result =  profitService.player_kiting(user);
			if(result==0){
				model.put("msg", " 提现申请已提交，两个工作日到账，请注意查收~");
			}else if(result==1){
				model.put("msg", " 收款信息不全,请在代理后台，个人中心补充收款信息~ ");
			}else if(result==2){
				model.put("msg", " 提现金额必须大于1元~ ");
			}
		}catch(Exception e){
			logger.error("查询单个俱乐部错误", e);
			model.put("statusCode", BootJsonResponse.STATUS_CODE_FAILURE);
		}
		return JsonUtil.toJson(model);
	}
	
	
	
	
	
}
